package cn.com.xy.sms.sdk.db.entity;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.DBManager;
import cn.com.xy.sms.sdk.db.XyCursor;
import cn.com.xy.sms.sdk.db.bizport.BizportDBManager;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.service.domainservice.DomainWhiteBean;
import cn.com.xy.sms.sdk.util.FileUtils;
import cn.com.xy.sms.sdk.util.StringUtils;

/**
 * @author kwb1
 * @version 1.0
 * @created 17-02-2017 16:37:50
 */
public class DomainDBManager {
    private final String TAG = "DomainDBManager";

    public final static String LOCAL_DOMAIN_WHITE_LIST_VERSION = "local_domain_white_list_version";

    private static final String TABLE_NAME = "tb_domain_white_list";

    private static final String KEY_ID = "_id";
    private static final String KEY_DOMAIN_NAME = "domain_name"; // 域名名称
    private static final String KEY_VERSION = "version"; // 域名版本
    private static final String KEY_PUB_ID = "pub_id";// 企业编号

    public static final String DROP_TABLE = " DROP TABLE IF EXISTS " + TABLE_NAME;

    public static final String CREATE_TABLE = "create table  if not exists " + TABLE_NAME + " (" + KEY_ID
            + " INTEGER PRIMARY KEY," + KEY_DOMAIN_NAME + " TEXT ," + KEY_PUB_ID + " VARCHAR ," + KEY_VERSION
            + " VARCHAR" + ")";

    private static DomainDBManager sDbManager;

    private DomainDBManager() {
    }

    public static DomainDBManager getInstance() {
        synchronized (DomainDBManager.class) {
            if (sDbManager == null) {
                sDbManager = new DomainDBManager();
            }
        }
        return sDbManager;
    }

    private void updateOrinsert(String companyNum, ContentValues values) {
        try {
            int row = BizportDBManager.update(TABLE_NAME, values, KEY_PUB_ID + " =?", new String[] { companyNum });
            if (row <= 0)
                BizportDBManager.insert(TABLE_NAME, values);
        }
        catch (Throwable t) {
            LogManager.e(TAG, "insert", t);
        }
    }

    public void updateData(List<DomainWhiteBean> domainList) {
        for (DomainWhiteBean data : domainList) {
            ContentValues values = new ContentValues();
            values.put(KEY_PUB_ID, data.getPubId());
            values.put(KEY_VERSION, data.getVersion());
            values.put(KEY_DOMAIN_NAME, data.getDomainName());
            updateOrinsert(data.getPubId(), values);
        }
    }

    public Map<String, String> queryAllCompanyNumInfo() {
        XyCursor cursor = null;
        Map<String, String> map = new HashMap<String, String>();
        try {
            cursor = BizportDBManager.query(TABLE_NAME, new String[] { KEY_PUB_ID, KEY_VERSION }, null, null);
            if (cursor != null) {
                int companyNumIndex = cursor.getColumnIndex(KEY_PUB_ID);
                int versionIndex = cursor.getColumnIndex(KEY_VERSION);
                while (cursor.moveToNext()) {
                    map.put(cursor.getString(companyNumIndex), cursor.getString(versionIndex));
                }
            }
        }
        catch (Throwable t) {
            LogManager.e(TAG, "queryAllCompanyNumInfo", t);
        }
        finally {
            XyCursor.closeCursor(cursor, true);
        }

        return map;
    }

    public String queryDomainByCompanyNum(String companyNum) {
        XyCursor cursor = null;
        String domain = null;
        try {
            cursor = BizportDBManager.query(TABLE_NAME, new String[] { KEY_DOMAIN_NAME }, KEY_PUB_ID + " =?",
                    new String[] { companyNum });
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    domain = cursor.getString(cursor.getColumnIndex(KEY_DOMAIN_NAME));
                }
            }
        }
        catch (Throwable t) {
            LogManager.e(TAG, "queryDomainByCompanyNum", t);
        }
        finally {
            XyCursor.closeCursor(cursor, true);
        }
        return domain;
    }

    public synchronized void initDataToDb() {
        InputStream is = null;
        BufferedReader buffreader = null;
        InputStreamReader inputreader = null;
        try {
            is = Constant.getContext().getAssets().open(Constant.DOMAIN_WHITE_LIST_FILE_NAME);
            inputreader = new InputStreamReader(is, "gbk");
            buffreader = new BufferedReader(inputreader);
            initDataToDB(buffreader);
        }
        catch (Throwable t) {
            LogManager.e(TAG, "initData", t);
        }
        finally {
            FileUtils.close(buffreader);
            FileUtils.close(inputreader);
            FileUtils.close(is);
        }
    }

    private void initDataToDB(BufferedReader bufferedReader) {
        LogManager.e(TAG, "start insertDataToDB");
        SQLiteDatabase db = null;
        try {
            android.database.sqlite.SQLiteStatement insert = null;
            android.database.sqlite.SQLiteStatement sqliteDelte = null;
            String str;
            String version = null;
            String localVersion = null;

            boolean isFirstLine = true;
            boolean isInsertNewData = false;
            String domainPubId = null;
            String domainName = null;
            while ((str = bufferedReader.readLine()) != null) {
                if (isFirstLine) {
                    // 第一行是版本，所以进行特殊判断
                    isFirstLine = false;
                    if (str.startsWith("PVER:")) {
                        version = str.substring(5, str.length());
                        localVersion = SysParamEntityManager.getStringParam(Constant.getContext(),
                                LOCAL_DOMAIN_WHITE_LIST_VERSION);
                        if (StringUtils.isNull(localVersion) || version.compareTo(localVersion) > 0) {// 版本比较
                            db = BizportDBManager.getSQLiteDatabase();
                            db.beginTransaction();
                            insert = db.compileStatement("INSERT INTO " + TABLE_NAME + "(" + KEY_PUB_ID + ","
                                    + KEY_DOMAIN_NAME + "," + KEY_VERSION + ")VALUES(?,?,?)");
                            sqliteDelte = db.compileStatement("DELETE FROM " + TABLE_NAME);
                            sqliteDelte.executeUpdateDelete();
                        }
                        else {
                            // 说明版本未更新,直接返回
                            break;
                        }
                    }
                    else {
                        LogManager.e(TAG, "DOMAIN_WHITE_LIST_IS_ERROR");
                        break;
                    }
                }
                else {
                    // 第二行开始是域名白名单数据
                    String array[] = str.split(",");
                    String pubid = array[0];
                    String domain = array[1];

                    if (StringUtils.isNull(domainPubId)) {
                        domainPubId = pubid;
                        domainName = domain;
                    }
                    else {

                        if (pubid.equals(domainPubId)) {
                            domainName += ";" + domain;
                        }
                        else {
                            insert.bindString(1, domainPubId);
                            insert.bindString(2, domainName);
                            insert.bindString(3, version);
                            insert.executeInsert();
                            domainName = domain;
                            domainPubId = pubid;
                        }
                    }
                }
            }

            if (!StringUtils.isNull(domainName) && !StringUtils.isNull(domainPubId)) {
                insert.bindString(1, domainPubId);
                insert.bindString(2, domainName);
                insert.bindString(3, version);
                insert.executeInsert();
            }

            if (StringUtils.isNull(localVersion) || version.compareTo(localVersion) > 0) {
                SysParamEntityManager.setParam(LOCAL_DOMAIN_WHITE_LIST_VERSION, version);
            }

            LogManager.e(TAG, "end Init DomainWhiteList");
        }
        catch (Throwable t) {
            LogManager.e(TAG, "insertDataToDB", t);
        }
        finally {
            if (db != null && db.inTransaction()) {
                db.setTransactionSuccessful();
                db.endTransaction();
            }
            BizportDBManager.close(db);
        }
    }

}